import 'dart:io';

import 'package:flutter/cupertino.dart';
import 'package:flutter/services.dart';
import 'package:flutter_ahj_app/base/utils/permission/PerUtils.dart';
import 'package:flutter_ahj_app/base/utils/permission/permissionGroup.dart';
import '../ToastUtils.dart';

import 'package:permission_handler/permission_handler.dart';
const MethodChannel _kChannel = MethodChannel('com.ahj/OpenFilePlugin');

class OpenFileUtils {
  // 传递有context对象的话就做权限判断，如果没有传递就不做权限判断（默认有权限）
  static open(String path, {Key key, BuildContext context}) async {
    if (path==null || path =="") {
      ToastUtils.showToast("文件路径不能为空");
      return;
    }
    String result = "1"; //默认有权限
    if (Platform.isAndroid) {
      if (context != null) {
      // 判断是否有文件读写权限
      result =
          await PerUtils.checkPermission(context, [Permission.storage]);
    }
    }

    if (result == "1") {
      // 判断文件是否存在
      File file = File(path);
      bool hasFile = await file.exists();
      if (!hasFile) {
        // 文件不存在
        ToastUtils.showToast("要打开的文件不存在");
        return;
      }
      Map<String, dynamic> map = Map();
      map["path"] = path;
      await _kChannel.invokeMethod('open_file', map);
    }
  }
}
